package com.haoran.dwz.web;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.haoran.dwz.domain.entities.Menu;
import com.haoran.dwz.domain.pojo.MenuVO;
import com.haoran.dwz.rest.R;
import com.haoran.dwz.service.MenuService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;

@Api(tags = { "Menus" }, description = "菜单管理",position=11)
@PreAuthorize("hasAuthority(\"role_admin\")")
@Controller
public class MenuController {
	@Autowired
	private MenuService menuService;
	
	@RequestMapping(value = "/sys/menus",method = RequestMethod.GET)
	public String index(HttpServletRequest  req , Model model) {
		 return "sys/menu";
	}
	
	
	@RequestMapping(value ="/sys/menulist",method = RequestMethod.GET)
	@ResponseBody
	public List<MenuVO> list(){
		List<MenuVO> ret = new ArrayList<>();
		List<Menu> menuList = menuService.findAll();
		for (Menu menu : menuList) {
			MenuVO vo = new MenuVO();
			vo.setId(menu.getId());
			vo.setIcon(menu.getIcon());
			vo.setName(menu.getName());
			vo.setParentId(menu.getParent() == null ? "0" : menu.getParent().getId());
			vo.setPerms(menu.getPermission());
			vo.setOrderNum(menu.getOrderNumber());
			vo.setParentName(menu.getParent() == null ? "" : menu.getParent().getName());
			ret.add(vo);
			Collection<Menu> children = menu.getChildren();
			
			for (Menu menu2 : children) {
				vo = new MenuVO();
				vo.setId(menu2.getId());
				vo.setIcon(menu2.getIcon());
				vo.setName(menu2.getName());
				vo.setParentId(menu2.getParent() == null ? "0" : menu2.getParent().getId());
				vo.setPerms(menu2.getPermission());
				vo.setOrderNum(menu2.getOrderNumber());
				vo.setParentName(menu2.getParent() == null ? "" : menu2.getParent().getName());
				ret.add(vo);
			}
		}
		return ret;
	}
	
	@ApiOperation("新增菜单")
	@RequestMapping(value = "/menus",method = RequestMethod.POST)
	@ResponseBody
	public R newAdd(Menu menu) {
		try {
			menuService.newAdd(menu);
			return R.success();
		} catch (Exception e) {
			return R.failure(e);
		}
	}
	
	@ApiOperation("编辑菜单")
	@RequestMapping(value = "/menus",method = RequestMethod.PUT)
	public R update(Menu menu) {
		try {
			menuService.update(menu);
			return R.success();
		} catch (Exception e) {
			return R.failure(e);
		}
	}
}
